﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Rewrite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using WeChat.CMS.Controllers;
using WeChat.CMS.OrganizationUnits;

namespace WeChat.CMS.Attachments
{
    [RemoteService(Name = "Attachment")]
    [ControllerName("Attachment")]
    [Route("api/attachment")]
    public class AttachmentController : CMSController
    {
        private readonly IAttachmentAppService _attachmentAppService;
        private readonly IAbpLazyServiceProvider _lazyServiceProvider;

        public AttachmentController(IAttachmentAppService attachmentAppService)
        {
            this._attachmentAppService = attachmentAppService;

        }

        [Route("SaveBlob")]
        [HttpPost]
        public async Task<AttachmentDTO> SaveBlobTest(IFormFile file)
        {
            var filebytes = file.GetAllBytes();
            string ext = Path.GetExtension(file.FileName);
            return await _attachmentAppService.AddAttachment(file.FileName, ext, file.ContentType, filebytes);
        }

        [Route("GetFile")]
        [HttpGet]
        public virtual async Task<IActionResult> GetFile(Guid Id)
        {
            try
            {
                var result = await _attachmentAppService.GetAttachment(Id);
                if(result == null)
                {
                    return NotFound();
                }else
                {
                    return File(result.FileBytes, result.ContentType, fileDownloadName: result.FileName);
                }
            }
            catch
            {
                return new NotFoundResult();
            }
            
        }
    }
}
